﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace ValidationFramework
{
	public class ParameterKey
	{
		MethodKey _methodKey { get; set; }
		string _paramName { get; set; }


		public MethodKey MethodKey
		{
			get
			{
				return _methodKey;
			}
		}
        ///// <summary>
		///// Initializes a new instance of the PropertyKey class.
		///// </summary>
		//public ParameterKey(RuntimeMethodHandle methodHandle)
		//{
		//    _methodHandle = methodHandle;
		//    _paramName = string.Empty;
		//}

		/// <summary>
		/// Initializes a new instance of the PropertyKey class.
		/// </summary>
		public ParameterKey(MethodKey methodKey, string paramName)
		{
			Guard.ArgumentNotNullOrEmptyString(paramName, "paramName");
			_methodKey = methodKey;
			_paramName = paramName;
		}

		public ParameterInfo ResolveParameterInfo()
		{
			if (string.IsNullOrEmpty(_paramName))
				return MethodInfo.GetMethodFromHandle(_methodKey.RuntimeMethodHandle).GetParameters().First();
			else
				return MethodInfo.GetMethodFromHandle(_methodKey.RuntimeMethodHandle).GetParameters().SingleOrDefault(x => x.Name == _paramName);
		}
		public Type ResolveParameterType()
		{
			return ResolveParameterInfo().ParameterType;
		}
		// To support using as a dictionary key
		public override bool Equals(object obj)
		{
			var key = (ParameterKey)obj;
			return this._methodKey.RuntimeMethodHandle.Equals(key._methodKey.RuntimeMethodHandle) && this._paramName == key._paramName;
		}

		public override int GetHashCode()
		{
			//TODO: this is probably a poor hash algorithm. Its probably ok, but if we can come up with a better one replace this.
			return _methodKey.RuntimeMethodHandle.GetHashCode() + _paramName.GetHashCode();
		}
	}
}
